package microphone;

import com.sun.media.sound.AudioFloatInputStream;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import javax.sound.sampled.*;

public class MicrophoneThread extends Thread {
    //

    private int sampleSize = 16;
    private int bufferSize = 1024;
    private float sampleRate = 8000.0f;
    //
    private AudioFormat format;
    private boolean running = true;
    //
    public LinkedBlockingQueue<float[]> signalQueue = new LinkedBlockingQueue<float[]>();
    //

    public MicrophoneThread() {
        format = new AudioFormat(sampleRate, sampleSize, 1, true, false);
    }

    public MicrophoneThread(int sampleSize, float sampleRate, int bufferSize) {
        format = new AudioFormat(sampleRate, sampleSize, 1, true, false);
        this.sampleSize = sampleSize;
        this.sampleRate = sampleRate;
        this.bufferSize = bufferSize;
    }

    @Override
    public void run() {
        TargetDataLine microphone = null;
        AudioFloatInputStream stream = null;

        try {

            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            microphone = (TargetDataLine) AudioSystem.getLine(info);
            stream =
                    AudioFloatInputStream.getInputStream(new AudioInputStream(microphone));

            microphone.open();
            microphone.start();

            running = true;
            while (running) {
                float[] buffer = new float[bufferSize];
                try {
                    stream.read(buffer, 0, bufferSize);
                } catch (IOException ex) {
                    System.err.println(ex);
                }
                signalQueue.add(buffer);
            }

            microphone.stop();
            microphone.close();
            
        } catch (LineUnavailableException ex) {

            System.err.println(ex + " error opening line: " + ex.getMessage());
            
        }
    }

    /**
     * Stop the recording.
     */
    public void stopRunning() {
        running = false;
    }

    

    /**
     * @return the format
     */
    public AudioFormat getFormat() {
        return format;
    }

    /**
     * @param format the format to set
     */
    public void setFormat(AudioFormat format) {
        this.format = format;
    }

    /**
     * @return the bufferSize
     */
    public int getBufferSize() {
        return bufferSize;
    }

    /**
     * @param bufferSize the bufferSize to set
     */
    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }
}
